# src/router/sys_manges.py
# from main import startup_event, shutdown_event
from src.crud import (sys_user as sysUserCrud,
                      sys_api_project as SysApiProjectCrud,
                      sys_api_teamwork as SysApiTeamworkCrud,
                      sys_field_mapping as SysFieldMappingCrud,
                      sys_organization as SysOrganizationCrud,
                      sys_table_mapping as SysTableMappingCrud,
                      sys_message as sysMessageCrud,
                      sys_menu as sysMenuCrud
                      )
from src.schemas import (sys_user as sysUserSchema,
                         sys_api_project as SysApiProjectSchema,
                         sys_api_teamwork as SysApiTeamworkSchema,
                         sys_field_mapping as SysFieldMappingSchema,
                         sys_organization as SysOrganizationSchema,
                         sys_table_mapping as SysTableMappingSchema,
                         sys_message as sysMessageSchema,
                         sys_menu as sysMenuSchema
                         )
# =============== 追加：实体国际化 CURD ===============
from src.crud import sys_entity_i18n as sysEntityI18nCrud
from src.schemas import sys_entity_i18n as sysEntityI18nSchemas

from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from src.core.ormdb import get_db
from src.schemas import request_model
from src.schemas.login_manager import AuthManager
from src.core import dependencies, retMes

router = APIRouter(
    # dependencies=[Depends(dependencies.auth_token)]  # ← 全局生效
    # prefix="/user",
    # tags=["sys_user"]  # ,
    # dependencies=[Depends(get_token_header)],
    # responses={404: {"description": "Not found"}},
    # description="Operations related to system users",
    # on_startup=[startup_event],
    # on_shutdown=[shutdown_event]
)


# 创建用户
#@router.post("/users/", response_model=list[sysUserSchema.SysUser])
@router.post("/users/batch", response_model=request_model.ResponseModel)
async def create_users(users: list[sysUserSchema.SysUserCreate],
                       db: Session = Depends(get_db),
                       # auth  = Depends()  # ← 占位即可，实际由路由级依赖注入
                       auth: AuthManager = Depends(dependencies.auth_token)
                       ):
    return sysUserCrud.create_users(db, auth, users)


# @router.post("/user/", response_model=sysUserSchema.SysUser)
@router.post("/users", response_model=request_model.ResponseModel)
async def create_user(user: sysUserSchema.SysUserCreate,
                      db: Session = Depends(get_db),
                      auth: AuthManager = Depends(dependencies.auth_token)
                      ):
    return sysUserCrud.create_user(db, auth, user)


# 获取用户
@router.get("/users/{id}", response_model=request_model.ResponseModel)
async def read_user(
        id: str,
        db: Session = Depends(get_db),
        auth: AuthManager = Depends(dependencies.auth_token)
):
    # 按 id 查单条
    db_user = sysUserCrud.get_users(db,
                                    auth,
                                    None,
                                    None,
                                    None,
                                    id)
    if not db_user:  # 查不到
        retMes.Raise(message="User not found").mes()  # 统一 401
    return db_user


# 获取所有用户
# @router.get("/users/", response_model=list[sysUserSchema.SysUser])
@router.get("/users", response_model=request_model.ResponseModel)
async def read_users(page: int = 1,
                     page_size: int = 100,
                     db: Session = Depends(get_db),
                     auth: AuthManager = Depends(dependencies.auth_token)
                     ):
    # 将页码转换为skip值
    # skip = (page - 1) * page_size
    return sysUserCrud.get_users(db,
                                 auth,
                                 page,
                                 page_size)


# 获取所有用户
# @router.post("/users/", response_model=list[sysUserSchema.SysUser])
@router.post("/users/query", response_model=request_model.ResponseModel)
async def read_users(queryModel: request_model.QueryModel = None,
                     db: Session = Depends(get_db),
                     auth: AuthManager = Depends(dependencies.auth_token)
                     ):
    # 将页码转换为skip值
    return sysUserCrud.get_users(db,
                                 auth,
                                 None,
                                 None,
                                 queryModel)


# 更新用户
@router.put("/users/{user_id}", response_model=request_model.ResponseModel)
async def update_user(user_id: str,
                      user: sysUserSchema.SysUser,
                      db: Session = Depends(get_db),
                      auth: AuthManager = Depends(dependencies.auth_token)):
    db_user = sysUserCrud.update_user(db,
                                      auth,
                                      user_id,
                                      user)
    if db_user is None:
        retMes.Raise(message="User not found").mes()  # 统一 401
    return db_user


@router.put("/users", response_model=request_model.ResponseModel)
async def update_user(updateModel: request_model.UpdateModel,
                      db: Session = Depends(get_db),
                      auth: AuthManager = Depends(dependencies.auth_token)):
    db_user = sysUserCrud.update_users(db,
                                       auth,
                                       updateModel)
    if db_user is None:
        retMes.Raise(message="User not found").mes()  # 统一 401

    return db_user


# 删除用户
@router.delete("/users", response_model=request_model.ResponseModel)
async def delete_user(deleteModel: request_model.DeleteModel,
                      db: Session = Depends(get_db),
                      auth: AuthManager = Depends(dependencies.auth_token)):
    db_user = sysUserCrud.delete_user(db,
                                      auth,
                                      deleteModel)
    if db_user is None:
        retMes.Raise(message="User not found").mes()  # 统一 401
    return db_user


# ========== 语言消息管理 ==========
@router.post("/messages", response_model=request_model.ResponseModel)
async def create_messages(
        messages: list[sysMessageSchema.SysMessageCreate],
        db: Session = Depends(get_db),
        auth: AuthManager = Depends(dependencies.auth_token)
):
    return sysMessageCrud.create_messages(db, auth, messages)


@router.post("/message", response_model=request_model.ResponseModel)
async def create_message(
        message: sysMessageSchema.SysMessageCreate,
        db: Session = Depends(get_db),
        auth: AuthManager = Depends(dependencies.auth_token)
):
    return sysMessageCrud.create_message(db, auth, message)


@router.get("/messages", response_model=request_model.ResponseModel)
async def read_messages(
        page: int = 1,
        page_size: int = 100,
        db: Session = Depends(get_db),
        auth: AuthManager = Depends(dependencies.auth_token)
):
    return sysMessageCrud.get_messages(db, auth, page, page_size)


@router.post("/messages/query", response_model=request_model.ResponseModel)
async def read_messages_query(
        queryModel: request_model.QueryModel = None,
        db: Session = Depends(get_db),
        auth: AuthManager = Depends(dependencies.auth_token)
):
    return sysMessageCrud.get_messages(db, auth, FilterModel=queryModel)


@router.put("/messages/{msg_id}", response_model=request_model.ResponseModel)
async def update_message(
        msg_id: str,
        message: sysMessageSchema.SysMessage,
        db: Session = Depends(get_db),
        auth: AuthManager = Depends(dependencies.auth_token)
):
    return sysMessageCrud.update_message(db, auth, msg_id, message)


@router.put("/messages", response_model=request_model.ResponseModel)
async def update_messages(
        updateModel: request_model.UpdateModel,
        db: Session = Depends(get_db),
        auth: AuthManager = Depends(dependencies.auth_token)
):
    return sysMessageCrud.update_messages(db, auth, updateModel)


@router.delete("/messages", response_model=request_model.ResponseModel)
async def delete_messages(
        deleteModel: request_model.DeleteModel,
        db: Session = Depends(get_db),
        auth: AuthManager = Depends(dependencies.auth_token)
):
    return sysMessageCrud.delete_messages(db, auth, deleteModel)


# ========== 菜单管理 ==========
@router.post("/menus/batch", response_model=request_model.ResponseModel)
async def create_menus(
        menus: list[sysMenuSchema.SysMenuCreate],
        db: Session = Depends(get_db),
        auth: AuthManager = Depends(dependencies.auth_token)
):
    return sysMenuCrud.create_menus(db, auth, menus)


@router.post("/menus", response_model=request_model.ResponseModel)
async def create_menu(
        menu: sysMenuSchema.SysMenuCreate,
        db: Session = Depends(get_db),
        auth: AuthManager = Depends(dependencies.auth_token)
):

    return sysMenuCrud.create_menu(db, auth, menu)


# 获取用户
@router.get("/menus/{id}", response_model=request_model.ResponseModel)
async def read_menu(
        id: str,
        db: Session = Depends(get_db),
        auth: AuthManager = Depends(dependencies.auth_token)
):
    # 按 id 查单条
    db_user = sysMenuCrud.get_menus(db,
                                    auth,
                                    None,
                                    None,
                                    None,
                                    id)
    if not db_user:  # 查不到
        retMes.Raise(message="User not found").mes()  # 统一 401
    return db_user


@router.get("/menus", response_model=request_model.ResponseModel)
async def read_menus(
        page: int = 1,
        page_size: int = 100,
        db: Session = Depends(get_db),
        auth: AuthManager = Depends(dependencies.auth_token)
):
    return sysMenuCrud.get_menus(db, auth, page, page_size)


@router.post("/menus/query", response_model=request_model.ResponseModel)
async def read_menus_query(
        queryModel: request_model.QueryModel = None,
        db: Session = Depends(get_db),
        auth: AuthManager = Depends(dependencies.auth_token)
):
    return sysMenuCrud.get_menus(db, auth, FilterModel=queryModel)


@router.put("/menus/{menu_id}", response_model=request_model.ResponseModel)
async def update_menu(
        menu_id: str,
        menu: sysMenuSchema.SysMenu,
        db: Session = Depends(get_db),
        auth: AuthManager = Depends(dependencies.auth_token)
):

    return sysMenuCrud.update_menu(db, auth, menu_id, menu)


@router.put("/menus", response_model=request_model.ResponseModel)
async def update_menus(
        updateModel: request_model.UpdateModel,
        db: Session = Depends(get_db),
        auth: AuthManager = Depends(dependencies.auth_token)
):
    return sysMenuCrud.update_menus(db, auth, updateModel)


@router.delete("/menus", response_model=request_model.ResponseModel)
async def delete_menus(
        deleteModel: request_model.DeleteModel,
        db: Session = Depends(get_db),
        auth: AuthManager = Depends(dependencies.auth_token)
):
    return sysMenuCrud.delete_menus(db, auth, deleteModel)


# 创建项目管理
@router.post("/projects", response_model=list[SysApiProjectSchema.SysApiProject])
async def create_projects(projects: list[SysApiProjectSchema.SysApiProjectCreate], db: Session = Depends(get_db)):
    return SysApiProjectCrud.create_SysApiProjects(db, projects)


@router.post("/project", response_model=SysApiProjectSchema.SysApiProject)
async def create_project(project: SysApiProjectSchema.SysApiProjectCreate, db: Session = Depends(get_db)):
    return SysApiProjectCrud.create_SysApiProject(db, project)


# 创建项目管理
@router.post("/projects", response_model=list[SysApiProjectSchema.SysApiProject])
async def create_projects(projects: list[SysApiProjectSchema.SysApiProjectCreate], db: Session = Depends(get_db)):
    return SysApiProjectCrud.create_SysApiProjects(db, projects)


@router.post("/project", response_model=SysApiProjectSchema.SysApiProject)
async def create_project(project: SysApiProjectSchema.SysApiProjectCreate, db: Session = Depends(get_db)):
    return SysApiProjectCrud.create_SysApiProject(db, project)


# 获取项目管理
# 获取单个项目管理
@router.get("/projects/{project_id}", response_model=SysApiProjectSchema.SysApiProject)
async def read_project(project_id: str, db: Session = Depends(get_db)):
    db_project = SysApiProjectCrud.get_api_project(db, project_id)
    if db_project is None:
        raise HTTPException(status_code=404, detail="Project not found")
    return db_project


# 获取所有项目管理
@router.get("/projects", response_model=list[SysApiProjectSchema.SysApiProject])
async def read_projects(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
    return SysApiProjectCrud.get_api_projects(db, skip, limit)


# 更新项目管理
@router.put("/projects/{project_id}", response_model=SysApiProjectSchema.SysApiProject)
async def update_project(project_id: str, project: SysApiProjectSchema.SysApiProjectCreate,
                         db: Session = Depends(get_db)):
    db_project = SysApiProjectCrud.update_api_project(db, project_id, project)
    if db_project is None:
        raise HTTPException(status_code=404, detail="Project not found")
    return db_project


# 删除项目管理
@router.delete("/projects/{project_id}")
async def delete_project(project_id: str, db: Session = Depends(get_db)):
    db_project = SysApiProjectCrud.delete_api_project(db, project_id)
    if db_project is None:
        raise HTTPException(status_code=404, detail="Project not found")
    return {"message": "Project deleted"}


# 创建项目协同
@router.post("/projectTeams", response_model=list[SysApiTeamworkSchema.SysApiTeamwork])
async def create_project_teamworks(projects: list[SysApiTeamworkSchema.SysApiTeamworkCreate],
                                   db: Session = Depends(get_db)):
    return SysApiTeamworkCrud.create_api_teamworks(db, projects)


@router.post("/projectTeam", response_model=SysApiTeamworkSchema.SysApiTeamwork)
async def create_project(project: SysApiTeamworkSchema.SysApiTeamworkCreate, db: Session = Depends(get_db)):
    return SysApiTeamworkCrud.create_api_teamwork(db, project)


# 获取项目协同
# 获取项目协同
@router.get("/projectTeams/{teamwork_id}", response_model=SysApiTeamworkSchema.SysApiTeamwork)
async def read_project_teamwork(teamwork_id: str, db: Session = Depends(get_db)):
    db_teamwork = SysApiTeamworkCrud.get_api_teamwork(db, teamwork_id)
    if db_teamwork is None:
        raise HTTPException(status_code=404, detail="Project Teamwork not found")
    return db_teamwork


@router.get("/projectTeams", response_model=list[SysApiTeamworkSchema.SysApiTeamwork])
async def read_project_teamworks(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
    return SysApiTeamworkCrud.get_api_teamworks(db, skip, limit)


# 更新项目协同
@router.put("/projectTeams/{teamwork_id}", response_model=SysApiTeamworkSchema.SysApiTeamwork)
async def update_project_teamwork(teamwork_id: str, teamwork: SysApiTeamworkSchema.SysApiTeamworkCreate,
                                  db: Session = Depends(get_db)):
    db_teamwork = SysApiTeamworkCrud.update_api_teamwork(db, teamwork_id, teamwork)
    if db_teamwork is None:
        raise HTTPException(status_code=404, detail="Project Teamwork not found")
    return db_teamwork


# 删除项目协同
@router.delete("/projectTeams/{teamwork_id}")
async def delete_project_teamwork(teamwork_id: str, db: Session = Depends(get_db)):
    db_teamwork = SysApiTeamworkCrud.delete_api_teamwork(db, teamwork_id)
    if db_teamwork is None:
        raise HTTPException(status_code=404, detail="Project Teamwork not found")
    return {"message": "Project Teamwork deleted"}


# 公司信息相关接口
# 创建公司信息
@router.post("/organizations", response_model=list[SysOrganizationSchema.SysOrganization])
async def create_organizations(organizations: list[SysOrganizationSchema.SysOrganizationCreate],
                               db: Session = Depends(get_db)):
    return SysOrganizationCrud.create_organizations(db, organizations)


@router.post("/organization", response_model=SysOrganizationSchema.SysOrganization)
async def create_organization(organization: SysOrganizationSchema.SysOrganizationCreate, db: Session = Depends(get_db)):
    return SysOrganizationCrud.create_organization(db, organization)


# 获取公司信息
@router.get("/organizations/{organization_id}", response_model=SysOrganizationSchema.SysOrganization)
async def read_organization(organization_id: str, db: Session = Depends(get_db)):
    db_organization = SysOrganizationCrud.get_organization(db, organization_id)
    if db_organization is None:
        raise HTTPException(status_code=404, detail="Organization not found")
    return db_organization


# 获取所有公司信息
@router.get("/organizations", response_model=list[SysOrganizationSchema.SysOrganization])
async def read_organizations(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
    return SysOrganizationCrud.get_organizations(db, skip, limit)


# 更新公司信息
@router.put("/organizations/{organization_id}", response_model=SysOrganizationSchema.SysOrganization)
async def update_organization(organization_id: str, organization: SysOrganizationSchema.SysOrganizationCreate,
                              db: Session = Depends(get_db)):
    db_organization = SysOrganizationCrud.update_organization(db, organization_id, organization)
    if db_organization is None:
        raise HTTPException(status_code=404, detail="Organization not found")
    return db_organization


# 删除公司信息
@router.delete("/organizations/{organization_id}")
async def delete_organization(organization_id: str, db: Session = Depends(get_db)):
    db_organization = SysOrganizationCrud.delete_organization(db, organization_id)
    if db_organization is None:
        raise HTTPException(status_code=404, detail="Organization not found")
    return {"message": "Organization deleted"}


# 表匹配相关接口
# 创建表匹配
@router.post("/tableMappings", response_model=list[SysTableMappingSchema.SysTableMapping])
async def create_table_mappings(mappings: list[SysTableMappingSchema.SysTableMappingCreate],
                                db: Session = Depends(get_db)):
    return SysTableMappingCrud.create_table_mappings(db, mappings)


@router.post("/tableMapping", response_model=SysTableMappingSchema.SysTableMapping)
async def create_table_mapping(mapping: SysTableMappingSchema.SysTableMappingCreate, db: Session = Depends(get_db)):
    return SysTableMappingCrud.create_table_mapping(db, mapping)


# 获取表匹配
@router.get("/tableMappings/{mapping_id}", response_model=SysTableMappingSchema.SysTableMapping)
async def read_table_mapping(mapping_id: str, db: Session = Depends(get_db)):
    db_mapping = SysTableMappingCrud.get_table_mapping(db, mapping_id)
    if db_mapping is None:
        raise HTTPException(status_code=404, detail="Table Mapping not found")
    return db_mapping


# 获取所有表匹配
@router.get("/tableMappings", response_model=list[SysTableMappingSchema.SysTableMapping])
async def read_table_mappings(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
    return SysTableMappingCrud.get_table_mappings(db, skip, limit)


# 更新表匹配
@router.put("/tableMappings/{mapping_id}", response_model=SysTableMappingSchema.SysTableMapping)
async def update_table_mapping(mapping_id: str, mapping: SysTableMappingSchema.SysTableMappingCreate,
                               db: Session = Depends(get_db)):
    db_mapping = SysTableMappingCrud.update_table_mapping(db, mapping_id, mapping)
    if db_mapping is None:
        raise HTTPException(status_code=404, detail="Table Mapping not found")
    return db_mapping


# 删除表匹配
@router.delete("/tableMappings/{mapping_id}")
async def delete_table_mapping(mapping_id: str, db: Session = Depends(get_db)):
    db_mapping = SysTableMappingCrud.delete_table_mapping(db, mapping_id)
    if db_mapping is None:
        raise HTTPException(status_code=404, detail="Table Mapping not found")
    return {"message": "Table Mapping deleted"}


# 字段匹配相关接口
# 创建字段匹配
@router.post("/fieldMappings", response_model=list[SysFieldMappingSchema.SysFieldMapping])
async def create_field_mappings(mappings: list[SysFieldMappingSchema.SysFieldMappingCreate],
                                db: Session = Depends(get_db)):
    return SysFieldMappingCrud.create_field_mappings(db, mappings)


@router.post("/fieldMapping", response_model=SysFieldMappingSchema.SysFieldMapping)
async def create_field_mapping(mapping: SysFieldMappingSchema.SysFieldMappingCreate, db: Session = Depends(get_db)):
    return SysFieldMappingCrud.create_field_mapping(db, mapping)


# 获取字段匹配
@router.get("/fieldMappings/{mapping_id}", response_model=SysFieldMappingSchema.SysFieldMapping)
async def read_field_mapping(mapping_id: str, db: Session = Depends(get_db)):
    db_mapping = SysFieldMappingCrud.get_field_mapping(db, mapping_id)
    if db_mapping is None:
        raise HTTPException(status_code=404, detail="Field Mapping not found")
    return db_mapping


# 获取所有字段匹配
@router.get("/fieldMappings", response_model=list[SysFieldMappingSchema.SysFieldMapping])
async def read_field_mappings(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
    return SysFieldMappingCrud.get_field_mappings(db, skip, limit)


# 更新字段匹配
@router.put("/fieldMappings/{mapping_id}", response_model=SysFieldMappingSchema.SysFieldMapping)
async def update_field_mapping(mapping_id: str, mapping: SysFieldMappingSchema.SysFieldMappingCreate,
                               db: Session = Depends(get_db)):
    db_mapping = SysFieldMappingCrud.update_field_mapping(db, mapping_id, mapping)
    if db_mapping is None:
        raise HTTPException(status_code=404, detail="Field Mapping not found")
    return db_mapping


# 删除字段匹配
@router.delete("/fieldMappings/{mapping_id}")
async def delete_field_mapping(mapping_id: str, db: Session = Depends(get_db)):
    db_mapping = SysFieldMappingCrud.delete_field_mapping(db, mapping_id)
    if db_mapping is None:
        raise HTTPException(status_code=404, detail="Field Mapping not found")
    return {"message": "Field Mapping deleted"}


# ---------- 单条新增 ----------
@router.post("/entity-i18n", summary="新增单条实体国际化", response_model=request_model.ResponseModel)
def create_entity_i18n(
        item: sysEntityI18nSchemas.SysEntityI18nCreate,
        db: Session = Depends(get_db),
        auth: AuthManager = Depends(dependencies.auth_token)
):
    return sysEntityI18nCrud.create_entity_i18n(db, auth, item)


# ---------- 批量新增 ----------
@router.post("/entity-i18n/batch", summary="批量新增实体国际化", response_model=request_model.ResponseModel)
def create_entity_i18ns(
        items: list[sysEntityI18nSchemas.SysEntityI18nCreate],
        db: Session = Depends(get_db),
        auth: AuthManager = Depends(dependencies.auth_token)
):
    return sysEntityI18nCrud.create_entity_i18ns(db, auth, items)


# ---------- 分页查询 ----------
@router.get("/entity-i18n", summary="分页查询实体国际化", response_model=request_model.ResponseModel)
def read_entity_i18ns(
        page: int = 1,
        page_size: int = 100,
        db: Session = Depends(get_db),
        auth: AuthManager = Depends(dependencies.auth_token)
):
    return sysEntityI18nCrud.get_entity_i18ns(db, auth, page, page_size)


# ---------- 条件查询 ----------
@router.post("/entity-i18n/query", summary="条件查询实体国际化", response_model=request_model.ResponseModel)
def query_entity_i18ns(
        query: request_model.QueryModel | None = None,
        db: Session = Depends(get_db),
        auth: AuthManager = Depends(dependencies.auth_token)
):
    return sysEntityI18nCrud.get_entity_i18ns(db, auth, FilterModel=query)


# ---------- 单条更新 ----------
@router.put("/entity-i18n/{pk}", summary="更新单条实体国际化")
def update_entity_i18n(
        pk: str,
        item: sysEntityI18nSchemas.SysEntityI18n,
        db: Session = Depends(get_db),
        auth: AuthManager = Depends(dependencies.auth_token)
):
    return sysEntityI18nCrud.update_entity_i18n(db, auth, pk, item)


# ---------- 批量更新 ----------
@router.put("/entity-i18n/batch", summary="批量更新实体国际化", response_model=request_model.ResponseModel)
def update_entity_i18ns(
        model: request_model.UpdateModel,
        db: Session = Depends(get_db),
        auth: AuthManager = Depends(dependencies.auth_token)
):
    return sysEntityI18nCrud.update_entity_i18ns(db, auth, model)


# ---------- 删除 ----------
@router.delete("/entity-i18n/batch", summary="删除实体国际化", response_model=request_model.ResponseModel)
def delete_entity_i18ns(
        model: request_model.DeleteModel,
        db: Session = Depends(get_db),
        auth: AuthManager = Depends(dependencies.auth_token)
):
    return sysEntityI18nCrud.delete_entity_i18ns(db, auth, model)
